﻿using HtmlAgilityPack;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Xml;

namespace APP
{
    class WeiXinNewsCrawler
    {
        private static CookieContainer _cookieContainer = new CookieContainer();

        private static List<Article> Articles = new List<Article>();
        public static bool Query(string keywords)
        {
            string url = "https://weixin.sogou.com/weixin?type=1&query=" + keywords;
            try
            {
                System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1, 0, 0, 0, 0));
                long t = (DateTime.Now.Ticks - startTime.Ticks) / 10000;
                _cookieContainer.Add(new Cookie("ABTEST", "0|" + t.ToString() + "|v1", "/", "weixin.sogou.com"));
                string result = HttpHelper.HttpGet(url, _cookieContainer);
                var html = new HtmlDocument();
                html.LoadHtml(result);
                var dd = html.DocumentNode.DescendantsAndSelf("a");
                foreach (var item in dd)
                {
                    if (item.Attributes["uigs"] != null)
                    {
                        if (item.Attributes["uigs"].Value == "account_image_0")
                        {
                            string ss = item.Attributes["href"].Value.Replace("&amp;", "&");
                            SeachList(ss, _cookieContainer);
                            break;
                        }
                    }
                }
                return true;
            }
            catch (Exception ex)
               {
                throw ex;
            }
        }


        //https://mp.weixin.qq.com

        private static void SeachList(string url, CookieContainer cookieContainer)
        {
            string result = HttpHelper.HttpGet(url, _cookieContainer);
            //"var\s*msgList\s*=\s*([\s\S]*)?};"
            Regex regex = new Regex(@"var\s*msgList\s*=\s*([\s\S]*)?};");
            var rr = regex.Matches(result);
            string strjson = rr[0].ToString().Replace("var msgList = ", "").ToString();
            strjson = strjson.Remove(strjson.Length - 1, 1);
            JObject jsonobj = JObject.Parse(strjson);
            var dd = jsonobj.GetValue("list");
            foreach (JToken item in dd)
            {
                var itemmsg = JObject.FromObject(JObject.FromObject(item).GetValue("app_msg_ext_info"));
                Articles.Add(new Article() { Title = itemmsg.GetValue("title").ToString(), ContextUrl = itemmsg.GetValue("content_url").ToString() });
                var multi_app_msg_item_list = itemmsg.GetValue("multi_app_msg_item_list");
                //multi_app_msg_item_list
                foreach (var multi in multi_app_msg_item_list)
                {
                    var multimsg = JObject.FromObject(multi);
                    Articles.Add(new Article() { Title = multimsg.GetValue("title").ToString(), ContextUrl = multimsg.GetValue("content_url").ToString() });
                }
            }
            GetUrlPage();
        }

        //private void 

        /// <summary>
        /// 获取网页html
        /// </summary>
        private static void GetUrlPage()
        {
            #region 获取xml资源文件
            string xmlPath = Environment.CurrentDirectory + "/files.xml";//获取 程序启动文件路径
            //获取 节点内容
            XmlDocument xml = new XmlDocument();
            xml.Load(xmlPath);//读取文件地址

            XmlElement root = xml.DocumentElement;//获取跟节点
            List<string> oldArticles = new List<string>();
            foreach (XmlNode item in root.ChildNodes)
            {
                string aa = item.Attributes["name"].Value.ToString();
                oldArticles.Add(aa);
            } 
            #endregion
            foreach (Article article in Articles)
            {
                #region 更新xml资源文件
                if (oldArticles.Contains(article.Title))
                {
                    continue;
                }
                var node = xml.CreateElement("news");
                node.SetAttribute("name", article.Title);
                string htmlpath =  @"\dowonload\" + Guid.NewGuid().ToString() + ".html";
                node.SetAttribute("value", htmlpath);
                
                root.AppendChild(node);
                //保存xml资源文件
                xml.Save(xmlPath);
                oldArticles.Add(article.Title);

                #endregion

                string url = "https://mp.weixin.qq.com" + article.ContextUrl.Replace("amp;", "");
                string result = HttpHelper.HttpGet("https://mp.weixin.qq.com" + article.ContextUrl.Replace("amp;", ""), _cookieContainer);
                var html = new HtmlDocument();
                html.LoadHtml(result);
                var dd = html.DocumentNode.DescendantsAndSelf("img");
                foreach (var item in dd)
                {
                    if (item.Attributes["data-src"] != null)
                    {
                        ImageSrc src = new ImageSrc
                        {
                            Url = item.Attributes["data-src"].Value
                        };
                        string picType;
                        if (src.Url.LastIndexOf("=") > 0)
                        {
                            picType = src.Url.Substring(src.Url.LastIndexOf("="));
                        }
                        else
                        {
                            picType = "=png";
                        }
                        picType = picType.Replace("=", ".");
                        if (string.IsNullOrWhiteSpace(picType))
                        {
                            picType = ".png";
                        }
                        src.Name = Guid.NewGuid() + picType;
                        src.PathName = @"\dowonload\src\";
                        FileHelper.DownloadWebFile(src.Url, src.Name, Environment.CurrentDirectory + src.PathName);
                        item.Attributes["data-src"].Value = src.PathName + src.Name;
                        if (item.Attributes["src"] == null)
                        {
                            HtmlAttribute attribute = item.Attributes["data-src"].Clone();
                            attribute.Name = "src";
                            attribute.Value = Environment.CurrentDirectory + src.PathName + src.Name;
                            item.Attributes.Add(attribute);
                        }
                        else
                        {
                            item.Attributes["src"].Value = Environment.CurrentDirectory + src.PathName + src.Name;
                        }

                    }
                    #region 匹配src异常，微信使用img标签为网页播放器，播放腾讯视频
                    //else if (item.Attributes["src"] != null)
                    //{
                    //    if (string.IsNullOrWhiteSpace(item.Attributes["src"].Value))
                    //    {
                    //        continue;
                    //    }
                    //    ImageSrc src = new ImageSrc();
                    //    src.Url = item.Attributes["src"].Value;
                    //    string picType;
                    //    if (src.Url.LastIndexOf("=") > 0)
                    //    {
                    //        picType = src.Url.Substring(src.Url.LastIndexOf("="));
                    //    }
                    //    else
                    //    {
                    //        picType = "=png";
                    //    }
                    //    picType = picType.Replace("=", ".");
                    //    if (string.IsNullOrWhiteSpace(picType))
                    //    {
                    //        picType = ".png";
                    //    }
                    //    src.Name = Guid.NewGuid() + picType;
                    //    src.PathName = @"\dowonload\src\";
                    //    FileHelper.DownloadWebFile(src.Url, src.Name, Environment.CurrentDirectory + src.PathName);
                    //    item.Attributes["src"].Value = src.PathName + src.Name;
                    //    item.Attributes["src"].Value = Environment.CurrentDirectory + src.PathName + src.Name;
                    //} 
                    #endregion
                }
                download(html, htmlpath);
            }
            
        }

        private static void download(HtmlDocument html,string htmlpath)
        {
            using (FileStream fs = new FileStream(Environment.CurrentDirectory+ htmlpath, FileMode.OpenOrCreate, FileAccess.Write))
            {
                html.Save(fs);
            }
        }
    }
    public class Article
    {
        /// <summary>
        /// 标题
        /// </summary>
        public string Title { get; set; }

        /// <summary>
        /// 
        /// </summary>
        public string ContextUrl { get; set; }


    }

    public class ImageSrc
    {
        public string Name { get; set; }

        public string PathName { get; set; }

        public string Url { get; set; }
    }
}
